#include "btimetool.h"
#include <chrono>
#include <ctime>

using namespace butils;

time_t timetool::timestamps()
{
    const auto& now = std::chrono::system_clock::now();
    return std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
}

time_t timetool::timestampms()
{
    const auto& now = std::chrono::system_clock::now();
    return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
}

std::string timetool::unix_to_sdate(time_t ts)
{
    struct std::tm ntm;
#ifdef _MSC_VER
    localtime_s(&ntm, &ts);
#else
    localtime_r(&ts, &ntm);
#endif // _MSC_VER
    char date[32]{ 0 };
    strftime(date, sizeof(date), "%Y-%m-%d", &ntm);
    return date;
}

std::string timetool::unix_to_stime(time_t ts)
{
    struct std::tm ntm;
#ifdef _MSC_VER
    localtime_s(&ntm, &ts);
#else
    localtime_r(&ts, &ntm);
#endif // _MSC_VER
    char date[32]{ 0 };
    strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", &ntm);
    return date;
}

time_t timetool::stime_to_unix(const std::string & stime)
{
    struct tm t_tm;
    memset(&t_tm, 0, sizeof(t_tm));
#ifdef _MSC_VER
    sscanf_s(stime.c_str(), "%04d-%02d-%02d %02d:%02d:%02d",
#else
    sscanf(stime.c_str(), "%04d-%02d-%02d %02d:%02d:%02d",
#endif // _MSC_VER
        &t_tm.tm_year, &t_tm.tm_mon, &t_tm.tm_mday,
        &t_tm.tm_hour, &t_tm.tm_min, &t_tm.tm_sec);
    t_tm.tm_year -= 1900;
    t_tm.tm_mon--;
    return mktime(&t_tm);
}

